// posts -----------------------------------------------------------------------

function post_details(id)
{
	target = BASE_URL + 'posts/details/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog("option", "title", "Détails de l'article");
		$('#popup_details').dialog('open');
	});
}


function post_delete(id)
{
	$.ajax({
		url: BASE_URL + 'posts/delete/' + id,
		success: function(result) {
			delete_object('#post_' + id);
			restore_url = BASE_URL + 'posts/restore/' + id;
			$.jGrowl('Actualité supprimée<br /><a href="' + restore_url + ">Annuler la suppression</a>", {sticky: true});
		},
		error: function(result) { alert("Impossible de supprimer cette actualité"); }
	});
}

$(function() {
	// remove a tag
	$('a.post-tag-remove').live('click', function() {
		$(this).closest('.post-tag').fadeOut(500, function() {
			$(this).remove();
			// update the hidden input
			tag_names = '';
			$('.post-tag').each(function(index) {
				tag_names += $.trim($(this).text()) + ';';
			});
			$('input[name=tag_names]').val(tag_names);
		});
		return false;
	});
	// append a tag
	$('a#post-tag-add').click(function() {
		tag_name = $.trim($('input#post-tag-value').val());
		if (tag_name) {
			icon_url = BASE_URL + '../images/icons/tag_blue_delete.png';
			html = '<span class="post-tag">' + tag_name +
				' <a href="#" class="post-tag-remove"><img class="icon" src="' + icon_url + '" /></a></span>';
			$('#post-tags-container').append(html);
			tag_names = $('input[name=tag_names]');
			tag_names.val(tag_names.val() + tag_name + ';');
		}
		$('input#post-tag-value').val('').focus();
		return false;
	});
});

// contents --------------------------------------------------------------------

function content_details(id)
{
	target = BASE_URL + 'contents/details/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog("option", "title", "Détails de la page");
		$('#popup_details').dialog('open');
	});
}

function content_delete(id)
{
	$.ajax({
		url: BASE_URL + 'contents/delete/' + id,
		success: function(result) {
			delete_object('#content_' + id);
			restore_url = BASE_URL + 'contents/restore/' + id;
			$.jGrowl('Page supprimée<br /><a href="' + restore_url + ">Annuler la suppression</a>", {sticky: true});
		},
		error: function(result) { alert("Impossible de supprimer cette page"); }
	});
}

// faq -------------------------------------------------------------------------

function faq_details(id)
{
	target = BASE_URL + 'faqs/details/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog("option", "title", "Détails de la question");
		$('#popup_details').dialog('open');
	});
}

function faq_delete(id)
{
	$.ajax({
		url: BASE_URL + 'faqs/delete/' + id,
		success: function(result) {
			delete_object('#faq_' + id);
			restore_url = BASE_URL + 'faqs/restore/' + id;
			$.jGrowl('Question supprimée<br /><a href="' + restore_url + ">Annuler la suppression</a>", {sticky: true});
		},
		error: function(result) { alert("Impossible de supprimer cette question"); }
	});
}

$(function () {
	$('#faq_sortable').sortable({
		placeholder: "sortable-place-holder",
		stop: function(event, ui) {
			target = BASE_URL + 'faqs/update_positions/';
			$.ajax({
				url: target,
				type: 'POST',
				data: $('#faq_sortable').sortable("serialize"),
				success: function(result) {
					$.jGrowl("Positions enregistrées");
					$(ui.item).effect('highlight', {duration: 1000});
				},
				error: function(result) {
					alert("Impossible de mettre à jour les positions");
				}
			});

		}
	});
});

// tags ------------------------------------------------------------------------

function tag_rename(id)
{
	target = BASE_URL + 'tags/rename_form/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog({
			title: "Renommer un tag",
			width: 300,
			buttons: {
				"Valider": function() {
					tag_name = $('#tag_form input[name=name]').val();
					$.ajax({
						url: BASE_URL + 'tags/rename/' + id,
						type: 'POST',
						data: { 'name': tag_name },
						success: function(result) {
							$('#tag_' + id + ' .name').html(tag_name);
							$('#popup_details').dialog('close');
							$.jGrowl("Tag renommé « " + tag_name + " »");
						},
						error: function(xhr, caca) {
							$('#tag_form div.error').remove();
							$('#tag_form').append(xhr.responseText);
						}
					});
				},
				"Annuler": function() {
					$(this).dialog('close');
				}
			}
		});
		$('#popup_details').dialog('open');
	});
}

function tag_delete(id)
{
	$.ajax({
		url: BASE_URL + 'tags/delete/' + id,
		success: function(result) {
			delete_object('#tag_' + id);
			$.jGrowl("Tag supprimé");
		},
		error: function(result) { alert("Impossible de supprimer ce tag"); }
	});
}

// menus -----------------------------------------------------------------------

var second_level_config = {
	handle: '.handle',
	connectWith: '.second-level',
	placeholder: 'placeholder',
	stop: function(event, ui) {
		receiver = $(ui.item).closest('.second-level');
		parent = receiver.closest('.first-level-item');
		$.ajax({
			url: BASE_URL + '/menus/update_items_positions/',
			type: 'POST',
			data: receiver.sortable('serialize') + '&parent_item_id=' + id_from_element(parent),
			success: function(result) {
				$.jGrowl("Positions enregistrées");
				$(ui.item).effect('highlight', {duration: 1000});
			},
			error: function(result) {
				alert("Impossible de mettre à jour les positions");
			}
		});
	}
}

$(function() {
	$('#menus_manager').sortable({
		stop: function(event, ui) {
			$.ajax({
				url: BASE_URL + '/menus/update_items_positions/',
				type: 'POST',
				data: $(this).sortable('serialize'),
				success: function(result) {
					$.jGrowl("Positions enregistrées");
					$(ui.item).effect('highlight', {duration: 1000});
				},
				error: function(result) {
					alert("Impossible de mettre à jour les positions");
				}
			});
		}
	});

	$('.second-level').sortable(second_level_config);

	// menu item form ----------------------------------------------------------

	// enable/disable form subparts
	$('#radio_content_link').live('change', function() {
		$('select[name=content_link]').removeAttr('disabled');
		$('select[name=intern_link]').attr('disabled', 'disabled');
		$('input[name=extern_link]').attr('disabled', 'disabled');
	}).change();
	$('#radio_intern_link').live('change', function() {
		$('select[name=content_link]').attr('disabled', 'disabled');
		$('select[name=intern_link]').removeAttr('disabled');
		$('input[name=extern_link]').attr('disabled', 'disabled');
	}).change();
	$('#radio_extern_link').live('change', function() {
		$('select[name=content_link]').attr('disabled', 'disabled');
		$('select[name=intern_link]').attr('disabled', 'disabled');
		$('input[name=extern_link]').removeAttr('disabled');
	}).change();
	$('#radio_no_link').live('change', function() {
		$('select[name=content_link]').attr('disabled', 'disabled');
		$('select[name=intern_link]').attr('disabled', 'disabled');
		$('input[name=extern_link]').attr('disabled', 'disabled');
	}).change();
});

function fill_name_from_select(select_name)
{
	// remplissage automatique de la textbox du nom
	current_opt = $('#menu_item_form select[name=' + select_name + '] option:selected').html();
	$('#menu_item_form input[name=name]').val(current_opt);
}

function menu_delete_item(id)
{
	$.ajax({
		url: BASE_URL + '/menus/delete_item/' + id,
		success: function(result) {
			delete_object('#menuitem_' + id);
			$.jGrowl("Élément de menu supprimé");
		},
		error: function(result) { alert("Impossible de supprimer ce menu"); }
	});
}

function menu_update_item(id, options)
{
	$('#popup_details').load(options.popup_target, function() {
		$('#popup_details').dialog({
			open: function(event, ui) {
				$('#menu_item_form input[type=radio]:checked').trigger('change');
			},
			title: options.form_title,
			buttons: {
				"Valider": function() {
					$.ajax({
						url: options.form_target,
						type: 'POST',
						data: $('#menu_item_form').serializeArray(),
						success: function(result) {
							// mise à jour des menu items
							$('#menus_manager').html(result);
							// les sortables de second-level ont été détruits, on rebind la config sortable
							$('.second-level').sortable(second_level_config);
							// les a.js-confirm ont été détruit également
							$('a.js-confirm').confirm({
								wrapper: '<span class="js-confirm-wrapper"></span>',
								msg:'<strong>Supprimer ?</strong><br />',
							  	timeout: 9000,
								buttons: {
									ok: '<span class="button-oui"></span>',
									cancel: '<span class="button-non"></span>',
									separator: ''
								}
							});
							$('#popup_details').dialog('close');
							$('#menuitem_' + id).effect('highlight', {duration: 1000});
							$.jGrowl("Élément de menu enregistré");
						},
						error: function(result) {
							alert(options.error_message);
						}
					});
				},
				"Annuler": function() {
					$(this).dialog('close');
				}
			},
		});

		$('#popup_details').dialog('open');
	});
}


function menu_edit_item(id)
{
	var options = {
		popup_target: BASE_URL + '/menus/get_item/' + id,
		form_title: "Éditer l'élément",
		form_submit: "Mettre à jour",
		form_target: BASE_URL + '/menus/update_item/' + id,
		error_message: "Impossible de mettre à jour l'élément"
	};
	menu_update_item(id, options);
}


function menu_add_item(menu_id, id)
{
	var options = {
		popup_target: BASE_URL + '/menus/blank_item/' + menu_id + '/' + id,
		form_title: id == 0 ? "Ajouter un élément" : "Ajouter un sous-élément",
		form_submit: "Créer",
		form_target: BASE_URL + '/menus/create_item/' + id,
		error_message: "Impossible de créer l'élément"
	};
	menu_update_item(id, options);
}

// users -----------------------------------------------------------------------

function user_delete(id)
{
	$.ajax({
		url: BASE_URL + 'candidats/user_delete/' + id,
		success: function(result) {
			delete_object('#user_' + id);
			$.jGrowl("Utilisateur supprimé");
		},
		error: function(result) { alert("Impossible de supprimer cet utilisateur"); }
	});
}

function user_details(id)
{
	target = BASE_URL + 'candidats/get/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog({
			title: "Détails de l'utilisateur"
		});
		$('.js-tabs').tabs();
		$('#popup_details').dialog('open');

	});
}

// email messages --------------------------------------------------------------


function email_delete(id)
{
	$.ajax({
		url: BASE_URL + 'emails/delete/' + id,
		success: function(result) {
			delete_object('#email_' + id);
			$.jGrowl("Message supprimé");
		},
		error: function(result) { alert("Impossible de supprimer ce message"); }
	});
}

function email_details(id)
{
	target = BASE_URL + 'emails/details/' + id;
	$('#popup_details').load(target, function() {
		$('#popup_details').dialog({title: "Détails du message"});
		$('#popup_details').dialog('open');
	});

}
// files -----------------------------------------------------------------------

function file_delete(filename, row_id)
{
	$.ajax({
		url: BASE_URL + 'medias/file_delete/',
		type: 'POST',
		data: {'filename': filename},
		success: function(result) {
			delete_object('#file_' + row_id);
			$.jGrowl("Fichier supprimé");
		},
		error: function(result) { alert("Impossible de supprimer ce fichier"); }
	});
}

// application settings --------------------------------------------------------

function setting_reset(id)
{
	setting = $('#setting_' + id);
	reset_value = $('input[name=reset_setting_' + id + ']').val();
	if (setting.attr('type') == 'checkbox') {
		setting.attr('checked', reset_value);
	}
	else {
		setting.val(reset_value);
	}
}

function setting_save(id)
{
	value = null;
	if ($('#setting_' + id).attr('type') == 'checkbox') {
		value = $('#setting_' + id).is(':checked') ? 1 : 0;
	}
	else {
		value = $('#setting_' + id).val();
	}
	$.ajax({
		url: BASE_URL + 'config/setting_save/' + id,
		type: 'POST',
		data: {'value': value},
		success: function(result) {
			$('#setting_' + id).closest('tr').effect('highlight', 3000);
			$.jGrowl("Paramètre enregistré");
		},
		error: function(result) { alert("La valeur du paramètre est invalide"); }
	});
}
